#region License, Terms and Conditions
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using Jayrock;
using Pesta.DataAccess;
using Pesta.DataAccess.Azure;
using Pesta.DataAccess.SqlServer;
using raya.Library;

namespace raya.Models.openid
{
    /// <summary>
    /// Summary description for openID
    /// </summary>
    public class openID
    {
#if AZURE
        public bool doesOpenIDExist(string openid)
        {
            using (var db = RayaDataContext.DB())
            {
                var exist = db.persons.Where(x => x.open_id == openid).SingleOrDefault();
                if (exist != null)
                {
                    return true;
                }
            }
            return false;
        }

        public string getUserID(string openid)
        {
            using (var db = RayaDataContext.DB())
            {
                var result = db.persons.Where(x => x.open_id == openid).SingleOrDefault();
                if (result != null)
                {
                    return result.open_id;
                }
                return "";
            }
        }

        public string add_new_openid_user(string openid, ClaimsResponse ext)
        {
            using (var db = RayaDataContext.DB())
            {
                var partitionKey = DateTime.UtcNow.Ticks.ToString();
                var newperson = new PersonRow(partitionKey, string.Empty);
                if (ext.Gender.HasValue)
                {
                    newperson.gender = ext.Gender.Value.ToString().ToLower();
                }
                if (ext.BirthDate.HasValue)
                {
                    newperson.date_of_birth = UnixTime.ToInt64(ext.BirthDate.Value);
                }
                string[] nameparts = ext.FullName.Split(' ');
                newperson.last_name = nameparts[0];
                newperson.first_name = string.Join(" ", nameparts.Skip(1).ToArray());
                newperson.email = ext.Email;
                newperson.email_hash = Utility.email_get_public_hash(ext.Email);
                newperson.open_id = openid;
                db.InsertOnSubmit(AzureRayaDataContext.TableNames.persons, newperson);
                db.SubmitChanges();
                var addr = new PersonAddressRow(partitionKey, string.Empty)
                               {
                                   country = ext.Country
                               };
                db.InsertOnSubmit(AzureRayaDataContext.TableNames.personAddresses, addr);
                db.InsertOnSubmit(AzureRayaDataContext.TableNames.personCurrentLocations, addr);
                db.SubmitChanges();
                return partitionKey;
            }
        }

        public void AttachOpenID(string openid, string userid)
        {
            using (var db = RayaDataContext.DB())
            {
                var result = db.persons.Where(x => x.id == userid).SingleOrDefault();
                if (result != null)
                {
                    result.open_id = openid;
                    db.UpdateOnSubmit(result);
                    db.SubmitChanges();
                }
            }
        }

#else
        public string getUserID(string openid)
        {
            using (var db = RayaDataContext.DB())
            {
                return db.openid_users.Where(x => x.openid_url == openid).Select(x => x.user_id).SingleOrDefault();
            }
        }
        public List<string> getOpenIDsByUserID(string userid)
        {
            List<string> vals = new List<string>();
            using (var db = RayaDataContext.DB())
            {
                var ids = db.openid_users.Where(x => x.user_id == userid).Select(x => x.openid_url);
                foreach (var id in ids)
                {
                    vals.Add(id);
                }
            }
            return vals;
        }
        public void AttachOpenID(string openid, string userid)
        {
            var data = new openid_user(){openid_url = openid, user_id = userid};
            using (var db = RayaDataContext.DB())
            {
                db.openid_users.InsertOnSubmit(data);
                db.SubmitChanges();
            }
        }
        public void DetachOpenID(string openid, string userid)
        {
            using (var db = RayaDataContext.DB())
            {
                var existing = db.openid_users.Where(x => x.user_id == userid && x.openid_url == openid).Select(x => x);
                db.openid_users.DeleteAllOnSubmit(existing);
                db.SubmitChanges();
            }
        }
        public void DetachOpenIDsByUser(string userid)
        {
            using (var db = RayaDataContext.DB())
            {
                var existing = db.openid_users.Where(x => x.user_id == userid).Select(x => x);
                db.openid_users.DeleteAllOnSubmit(existing);
                db.SubmitChanges();
            }
        }
        public bool doesOpenIDExist(string openid)
        {
            using (var db = RayaDataContext.DB())
            {
                var exist = db.openid_users.Where(x => x.openid_url == openid).Count();
                if (exist > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public int add_new_openid_user(string openid, ClaimsResponse ext)
        {
            using (var db = RayaDataContext.DB())
            {
                var newperson = new person();

                if (ext.Gender.HasValue)
                {
                    newperson.gender = ext.Gender.Value.ToString().ToLower();
                }
                if (ext.BirthDate.HasValue)
                {
                    newperson.date_of_birth = UnixTime.ToInt64(ext.BirthDate.Value);
                }
                string[] nameparts = ext.FullName.Split(' ');
                newperson.last_name = nameparts[0];
                newperson.first_name = string.Join(" ", nameparts.Skip(1).ToArray());
                newperson.password = "";
                newperson.email = ext.Email;
                newperson.email_hash = Utility.email_get_public_hash(ext.Email);
                db.persons.InsertOnSubmit(newperson);
                db.SubmitChanges();
                address newaddress = new address {country = ext.Country};
                db.addresses.InsertOnSubmit(newaddress);
                db.SubmitChanges();
                person_current_location newloc = new person_current_location{ address_id = newaddress.id, person_id = newperson.id};
                db.person_current_locations.InsertOnSubmit(newloc);
                openid_user newuser = new openid_user{openid_url = openid, user_id = newperson.id.ToString()};
                db.openid_users.InsertOnSubmit(newuser);
                db.SubmitChanges();
                return newperson.id;
            }
        }
#endif


        
    }
}